<template>
  <el-col class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类Id" prop="typeId">
        <div class="block">
          <el-cascader
            v-model="typeValue"
            :options="typeList"
            :props="{label:'typeName',value:'typeId'}"
          ></el-cascader>
        </div>
      </el-form-item>
      <el-form-item label="品牌" prop="brandId">
        <template>
          <el-select v-model="queryParams.brandId" placeholder="请选择品牌">
            <el-option
              v-for="brand in brandList"
              :key="brand.brandId"
              :label="brand.brandName"
              :value="brand.brandId">
            </el-option>
          </el-select>
        </template>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品Id" align="center" prop="productId">
        <template slot-scope="scope">
          {{scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="商品主图" align="center">
        <template slot-scope="scope">
          <image-preview :src="scope.row.productMasterMap"></image-preview>
        </template>
      </el-table-column>
      <el-table-column label="商品轮播图" align="center" prop="productSlideshow">
        <template slot-scope="scope">
          <image-preview :src="scope.row.productSlideshow"></image-preview>
        </template>
        <div class="block">
          <span class="demonstration"></span>
          <el-carousel height="150px">
            <el-carousel-item v-for="item in 4" :key="item">
              <h3 class="small">{{ item }}</h3>
            </el-carousel-item>
          </el-carousel>
        </div>
      </el-table-column>
      <el-table-column label="商品描述" align="center" prop="productDescriber" />
      <el-table-column label="商品上下架状态" align="center" prop="productStatus">
        <template slot-scope="scope">
          <el-tooltip :content="'Switch value: ' + value" placement="top">
            <el-switch
              v-model="scope.row.productStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="0"
              @change="productPutaway(scope.row.productId,scope.row.productStatus)">
            </el-switch>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="商品是否包邮" align="center" prop="productMailStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.productMailStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="商品单位" align="center" prop="productUnit" />
      <el-table-column label="商品销量" align="center" prop="productSales" />
      <el-table-column label="商品添加时间" align="center" prop="productTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品牌名称" align="center" prop="brandName" />
      <el-table-column label="分类名称" align="center" prop="typeName" />
      <el-table-column label="商品是否删除" align="center" prop="isDelete">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.isDelete"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:product:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="100%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分片等">
          <template>
            <div class="dashboard-editor-container">
              <el-upload
                class="upload-demo"
                action=""
                ref="upload"
                :file-list="fileList"
                :limit="2"
                :on-change="handleChange"
                :on-remove="handleRemove"
                :auto-upload="false"
                accept=""
              >
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitFormOss">上传到服务器</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="resumeUpload">继续</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="stopUplosd">暂停</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="abortMultipartUpload">清除切片</el-button>
              </el-upload>
              <el-progress :percentage="percentage" :status="uploadStatus"></el-progress>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品主图" prop="productMasterMap">
<!--          <el-input v-model="form.productMasterMap" type="textarea" placeholder="请输入内容" />-->
          <el-upload class="avatar-uploader" action="/dev-api/product/product/upload"
                     :show-file-list="false" :on-success="handleAvatarSuccess">
<!--            /dev-api/product/brand/uploadLogo-->
            <img v-if="form.productMasterMap" :src="form.productMasterMap" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
<!--          <el-upload action="http://localhost:88/dev-api/product/product/upload" class="upload-demo"-->
<!--                     :on-success="uploadFilecarouselImages"-->
<!--                     :on-remove="handleRemove" :file-list="filecarouselImagesList"-->
<!--                     :on-exceed="handleExceed"-->
<!--                     list-type="picture">-->
<!--            <el-button size="small" type="primary">点击上传</el-button>-->
<!--            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
<!--          </el-upload>-->
        </el-form-item>
        <el-form-item label="商品轮播图">
            <div>
              <el-input v-model="form.productSlideshow" class="input-width" v-if="form.productSlideshow === null"></el-input>

              <el-upload
                :multiple="multiple"
                action="/http://localhost:88/dev-api/product/product/upload"
                list-type="picture-card"
                :auto-upload="false"
                ref="uploadPic"
                :file-list="fileListImages"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
            <div>
              <center>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleAddSomePicsInfo = false">取 消</el-button>
                <el-button type="primary" @click="addSomePeoplePicsForm">上传图片</el-button>
            </span>
              </center>
            </div>
<!--          <el-upload-->
<!--            class="avatar-uploader"-->
<!--            action="/dev-api/product/product/upload"-->
<!--            :show-file-list="false"-->
<!--            :on-success="handleAvatarSuccess2">-->
<!--&lt;!&ndash;                        /dev-api/product/brand/uploadLogo&ndash;&gt;-->
<!--            <img v-if="form.productSlideshow" :src="form.productSlideshow" class="avatar">-->
<!--            <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--          </el-upload>-->
        </el-form-item>
        <el-form-item label="商品描述">
          <editor v-model="form.productDescriber" :min-height="192"/>
        </el-form-item>
        <el-form-item label="商品上下架状态">
          <el-radio-group v-model="form.productStatus">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品是否包邮">
          <el-radio-group v-model="form.productMailStatus">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品单位" prop="productUnit">
          <el-input v-model="form.productUnit" placeholder="请输入商品单位" />
        </el-form-item>
        <el-form-item label="商品销量" prop="productSales">
          <el-input v-model="form.productSales" placeholder="请输入商品销量" />
        </el-form-item>
        <el-form-item label="类型" prop="typeId">
          <!--          <el-input v-model="form.typeId" placeholder="请输入分类Id" />-->
          <div class="block">
            <el-cascader
              v-model="typeValue"
              :options="typeList"
              :props="{label:'typeName',value:'typeId'}"
              @change="getModule"
            ></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <template>
            <el-select v-model="form.brandId" placeholder="请选择品牌">
              <el-option
                v-for="brand in brandList"
                :key="brand.brandId"
                :label="brand.brandName"
                :value="brand.brandId">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <l-cole v-show="form.ruleAttrId != ''" :span="24">
          <el-form :inline="true" :model="ruleTableBody" class="demo-form-inline">
            <el-form-item label="编号">
              <el-input style="width: 120px;" v-model="ruleTableBody.number" placeholder="编号"></el-input>
            </el-form-item>
            <el-form-item label="进价">
              <el-input-number style="width: 120px;" v-model="ruleTableBody.purchasePrice" controls-position="right" :min="0" :max="999999" :precision="2"></el-input-number>
            </el-form-item>
            <el-form-item label="价格">
              <el-input-number style="width: 120px;" v-model="ruleTableBody.price" controls-position="right" :min="0" :max="999999" :precision="2"></el-input-number>
            </el-form-item>
            <el-form-item label="售价">
              <el-input-number style="width: 120px;" v-model="ruleTableBody.sellingPrice" controls-position="right" :min="0" :max="999999" :precision="2"></el-input-number>
            </el-form-item>
            <el-form-item label="库存">
              <el-input-number style="width: 120px;" v-model="ruleTableBody.stock" controls-position="right" :min="0" :max="999999"></el-input-number>
            </el-form-item>
            <el-form-item label="重量">
              <el-input-number style="width: 120px;" v-model="ruleTableBody.weight" controls-position="right" :min="0" :max="999999" :precision="2"></el-input-number>
            </el-form-item>
            <el-form-item label="体积">
              <el-input-number style="width: 120px;" v-model="ruleTableBody.volume" controls-position="right" :min="0" :max="999999" :precision="2"></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button style="width: 120px;" type="primary" @click="oneClickSettings()">一键填充</el-button>
            </el-form-item>
          </el-form>
        </l-cole>
        <el-col  v-show="form.ruleAttrId != ''" :span="24">
          <el-table :data="ruleTableBodyList" height="500">
            <el-table-column v-for="ruleTableTitle in ruleTableTitleList" :label="ruleTableTitle.label" :prop="ruleTableTitle.prop" :width="ruleTableTitle.prop == 'image' ? '200px' : '0'">
              <template slot-scope="scope">
                <span v-if="ruleTableBodyInput.indexOf(ruleTableTitle.prop) == -1 && ruleTableTitle.prop != 'image'">{{scope.row[ruleTableTitle.prop]}}</span>
                <el-input v-if="ruleTableBodyInput.indexOf(ruleTableTitle.prop) > -1 && ruleTableTitle.prop != 'image'" v-model="scope.row[ruleTableTitle.prop]"></el-input>
                <el-upload class="avatar-uploader" action="/dev-api/product/product/upload"
                           :show-file-list="false" :on-success="imgSuccess"  v-if="ruleTableTitle.prop == 'image'">
                  <img v-if="scope.row[ruleTableTitle.prop]" :src=" scope.row[ruleTableTitle.prop] " class="avatar"/>
                  <i v-else class="el-icon-plus avatar-uploader-icon" @click="updateRuleTableBodyIndex(scope.$index)"></i>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-link type="primary" @click="deleteRuleTableBodyRow(scope.$index)" >移除</el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
<!--        <el-form-item label="规格信息" prop="productRuleAttrId">-->
<!--          <el-input v-model="form.productRuleAttrId" placeholder="请输入规格信息" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="商品是否删除" prop="isDelete">-->
<!--          <el-input v-model="form.isDelete" placeholder="请输入商品是否删除" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    </el-col>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct, productPutaway, productSold, uploadFileAll } from '@/api/product/product'
import { getBrandList } from '@/api/product/brand'
import { listType, getModuleMap } from '@/api/product/type'
let OSS = require('ali-oss') // 引入ali-oss插件
const client = new OSS({
  region: 'oss-cn-hangzhou',//根据那你的Bucket地点来填写
  accessKeyId: 'LTAI5tQqaMREaYTJYosRjMBa',//自己账户的accessKeyId
  accessKeySecret: 'phbs0nqOQ45t4kN52dV72kB0pCXb4j',//自己账户的accessKeySecret
  bucket: 'zhuifeng-oss',//bucket名字
});

export default {
  name: "Product",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      fileListImages: [],
      //图片上传的下标位置
      ruleTableBodyIndex: null,
      //类型的数级对象
      treeTypeList: [],
      //商品品牌列表
      productBrandList: [],
      //商品维护状态
      productEditStatus: 1,
      ruleList: [],
      ruleTableTitleListTemplate: [
        {label: "编号",prop: "number"},
        {label: "进价",prop: "purchasePrice"},
        {label: "价格",prop: "price"},
        {label: "售价",prop: "sellingPrice"},
        {label: "库存",prop: "stock"},
        {label: "图片",prop: "image"},
        {label: "重量",prop: "weight"},
        {label: "体积",prop: "volume"}
      ],
      ruleTableTitleList: [],
      ruleTableBodyInput: ["number","purchasePrice","price","sellingPrice","stock","weight","volume"],
      ruleTableBodyList: [],
      ruleTableBodyTemplate: {
        stock: '',
        price: '',
        purchasePrice: '',
        sellingPrice: '',
        image: '',
        number: '',
        weight: '',
        volume: ''
      },
      ruleTableBody: {
        number: '',
        stock: '',
        price: '',
        purchasePrice: '',
        sellingPrice: '',
        weight: '',
        volume: ''
      },
      fileList:[],
      file: null,
      tempCheckpoint: null, // 用来缓存当前切片内容
      uploadId: '',
      uploadStatus: null, // 进度条上传状态
      percentage: 0, // 进度条百分比
      uploadName: '', //Object所在Bucket的完整路径
      // 遮罩层
      loading: true,
      dialogVisible: false,
      brandList: [],
      typeList: [],
      typeValue: [],
      typeParams: {
        parentId: null
      },
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        brandId: null,
        typeId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        isDelete: [
          { required: true, message: "商品是否删除不能为空", trigger: "blur" }
        ],
      }
    };
  },
  mounted() {
    // window.addEventListener('online', this.resumeUpload);
  },
  created() {
    this.getList();
    this.listTypeLsit();
    if (this.isEdit) {
      findIntegralGiftsInfoById(this.$route.query.id).then(response => {
        this.homeAdvertise = response.data;
        let urlStr = response.data.picture.split(","); //logo地址
        urlStr.forEach(item => {
          let obj = new Object();
          obj.url = item;
          this.fileList.push(obj);
        });
      });
    }else{
      this.homeAdvertise = Object.assign({},defaultHomeAdvertise);
    }
  },
  methods: {
    productPutaway(productId,productStatus) {
      if (productStatus == 1){
        productPutaway(productId)
      }else {
        productSold(productId)
      }
    },
    updateRuleTableBodyIndex(index) {
      this.ruleTableBodyIndex = index;
    },
    imgSuccess(res, file) {
      this.ruleTableBodyList[this.ruleTableBodyIndex].image = res;
    },
    getModule() {
      getModuleMap(this.typeValue[this.typeValue.length - 1]).then(response => {
        this.brandList = response.data.brands;
        let ruleAttrJson = JSON.parse(response.data.productRule.rultAttr);
        //表单的表头
        let ruleTitle = [];
        // 变淡的表头 前缀
        let prop = "prop";
        let propArr = [];
        // 表单 body 的 属性值
        let valuesArr = [];
        ruleAttrJson.forEach(({key, values}, index) => {
          ruleTitle.push({"label": key, "prop": prop + index})
          propArr.push((prop + index));
          valuesArr.push(values)
        })
        //表头
        //console.log(ruleTitle)
        //body的对象
        let ruleAttrBodyList = [];
        //多少条记录
        let ruleAttrBodyListSize = 1;
        valuesArr.forEach((values) => {
          ruleAttrBodyListSize = ruleAttrBodyListSize * values.length
        })
        for (let i = 0 ; i < ruleAttrBodyListSize; i++) {
          let ruleAttrBody = {...this.ruleTableBodyTemplate};
          propArr.forEach((prop) => {
            ruleAttrBody[prop] = '';
          })
          ruleAttrBodyList.push(ruleAttrBody);
        }
        valuesArr.forEach((values, valuesIndex) => {
          //位置
          let prop = "prop" + valuesIndex
          //出现次数
          let forNum = 1;
          for (let i = 0; i < valuesIndex; i++) {
            forNum = forNum * valuesArr[i].length;
          }
          //循环次数
          let showNum = 1;
          for (let i = valuesIndex + 1; i < valuesArr.length; i++) {
            showNum = showNum * valuesArr[i].length
          }
          let valueIndex = 0;
          for (let i = 0; i < forNum; i++) {
            values.forEach((value) => {
              for (let j = 0; j < showNum; j++) {
                ruleAttrBodyList[valueIndex++][prop] = value
              }
            })
          }
        })
        console.log(valuesArr);
        console.log(ruleAttrBodyList)
        this.ruleTableBodyList = ruleAttrBodyList;

        //重量 体积 价格 ->内存 存储
        this.ruleTableTitleListTemplate.forEach((ruleTableTitle) => {
          ruleTitle.push(ruleTableTitle)
        })
        this.ruleTableTitleList = ruleTitle;
      })
    },
    /** 删除*/
    deleteRuleTableBodyRow(rowIndex){
      this.ruleTableBodyList.splice(rowIndex,1)
    },
    // 一键填充
    oneClickSettings(){
      let number = 1;
      for (let ruleTableBodyKey in this.ruleTableBody) {
        this.ruleTableBodyList.forEach((ruleBody) => {
          if (ruleTableBodyKey == "number"){
            ruleBody[ruleTableBodyKey] = this.ruleTableBody[ruleTableBodyKey] + (number++)
          }else {
            ruleBody[ruleTableBodyKey] = this.ruleTableBody[ruleTableBodyKey]
          }
        })
      }
    },
    submitFormOss(file) {
      this.multipartUpload();
    },
    handlePictureCardPreview(file) {
      this.form.productSlideshow = file.url;
      this.dialogVisible = true;
    },
    getTypeValueTo(typeList) {
      typeList.forEach((type) => {
        if (type.children != null){
          this.getTypeValueTo(type.children)
        }
        if (this.typeValue[0] == type.typeId && type.parentId != 0){
          var typeIds = this.typeValue.toString()
          typeIds = type.parentId + "," + typeIds
          this.typeValue = typeIds.split(",")
        }
      })
    },
    /** 查询类型列表 */
    listTypeLsit() {
      listType(this.queryParams.parentId).then(response => {
        this.typeList = this.handleTree(response.data, "typeId", "parentId");
      });
    },
    handleAvatarSuccess2(res, file) {
      this.form.productSlideshow = res
    },
    handleAvatarSuccess(res, file) {
      this.form.productMasterMap = res
    },
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        productName: null,
        productMasterMap: null,
        productSlideshow: null,
        productDescriber: null,
        productStatus: "0",
        productMailStatus: "0",
        productUnit: null,
        productSales: null,
        productTime: null,
        brandId: null,
        typeId: null,
        isDelete: null,
        revision: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        productRuleCenterList: []
      };
      this.resetForm("form");
      this.typeValue = [];
      this.brandList = [];
      this.ruleTableBodyList = [];
      this.ruleTableBody = {
        stock: '',
        price: '',
        purchasePrice: '',
        sellingPrice: '',
        image: '',
        number: '',
        weight: '',
        volume: ''
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const productId = row.productId || this.ids
      getProduct(productId).then(response => {
        this.typeValue.push(Number(response.data.typeId))
        this.getTypeValueTo(this.typeList)
        this.getBrandList(response.data.typeId)
        this.form = response.data;
        let productRuleCenterList = this.form.productRuleCenterList
        productRuleCenterList.forEach((productRule) => {
          let  props = productRule.sku.split(",")
          props.forEach((prop,index) => {
            productRule["prop" + index] = prop;
          })
        })
        this.ruleTableBodyList = productRuleCenterList;
        this.ruleTableTitleList = [];
        this.ruleList.forEach((rule) => {
          if (rule.id == this.form.ruleAttrId){
            const {ruleAttr} = rule;
            let ruleAttrJson = JSON.parse(ruleAttr);
            ruleAttrJson.forEach((attr, index) => {
              this.ruleTableTitleList.push({label:attr.key,prop:"prop" + index})
            })
          }
        })
        this.ruleTableTitleListTemplate.forEach((ruleTableTitle) => this.ruleTableTitleList.push(ruleTableTitle))

        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 获取品牌列表 */
    getBrandList(typeId) {
      getBrandList(typeId).then(response => {
        this.brandList = response.data;
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.form.typeId = this.typeValue[this.typeValue.length - 1]
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.ruleTableBodyList.forEach((ruleTableBody) => {
            let  sku = []
            for (let ruleTableBodyKey in ruleTableBody){
              if (ruleTableBodyKey.indexOf("prop")> -1){
                sku.push(ruleTableBody[ruleTableBodyKey])
              }
            }
            ruleTableBody['sku'] = sku.toString()
          })
          this.form.productRuleCenterList = this.ruleTableBodyList;
          if (this.form.productId != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + productIds + '"的数据项？').then(function() {
        return delProduct(productIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
    // 取消分片上传事件
    async abortMultipartUpload() {
      window.removeEventListener('online', this.resumeUpload)
      const name = this.uploadName; // Object所在Bucket的完整路径。
      const uploadId = this.upload; // 分片上传uploadId。
      const result = await client.abortMultipartUpload(name, uploadId);
      console.log(result, '=======清除切片====');
    },
    // 暂停分片上传。
    stopUplosd () {
      window.removeEventListener('online', this.resumeUpload) // 暂停时清除时间监听
      let result = client.cancel();
      console.log( result, '---------暂停上传-----------')
    },
    // 切片上传
    async multipartUpload () {
      if (!this.file) {
        this.$message.error('请选择文件')
        return
      }
      this.uploadStatus = null
      // console.log("this.uploadStatus",this.file, this.uploadStatus);

      this.percentage = 0
      try {
        //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
        let result = await client.multipartUpload(this.file.name, this.file, {
          headers: {
            'Content-Disposition': 'inline',
            'Content-Type': this.file.type //注意：根据图片或者文件的后缀来设置，我试验用的‘.png'的图片，具体为什么下文解释
          },
          progress: (p, checkpoint) => {
            this.tempCheckpoint = checkpoint;
            this.upload = checkpoint.uploadId
            this.uploadName = checkpoint.name
            this.percentage = p * 100
            // console.log(p, checkpoint, this.percentage, '---------uploadId-----------')
            // 断点记录点。浏览器重启后无法直接继续上传，您需要手动触发上传操作。
          },
          meta: { year: 2020, people: 'dev' },
          mime: this.file.type
        });
        console.log(result, this.percentage, 'result= 切片上传完毕=');
      } catch (e) {
        window.addEventListener('online', this.resumeUpload) // 该监听放在断网的异常处理
        // 捕获超时异常。
        if (e.code === 'ConnectionTimeoutError') { // 请求超时异常处理
          this.uploadStatus = 'exception'
          console.log("TimeoutError");
          // do ConnectionTimeoutError operation
        }
        // console.log(e)
      }
    },
    // 恢复上传。
    async resumeUpload () {
      window.removeEventListener('online', this.resumeUpload)
      if (!this.tempCheckpoint) {
        this.$message.error('请先上传')
        return
      }
      this.uploadStatus = null
      try {
        let result = await client.multipartUpload(this.file.name, this.file, {
          headers: {
            'Content-Disposition': 'inline',
            'Content-Type': this.file.type //注意：根据图片或者文件的后缀来设置，我试验用的‘.png'的图片，具体为什么下文解释
          },

          progress: (p, checkpoint) => {
            this.percentage = p * 100
            console.log(p, checkpoint, 'checkpoint----恢复上传的切片信息-------')
            this.tempCheckpoint = checkpoint;
          },
          checkpoint: this.tempCheckpoint,
          meta: { year: 2020, people: 'dev' },
          mime: this.file.type
        })
        console.log(result, 'result-=-=-恢复上传完毕')
      } catch (e) {
        console.log(e, 'e-=-=-');
      }
    },

    // 选择文件发生改变
    handleChange(file, fileList) {
      this.fileList = fileList.filter(row => row.uid == file.uid)
      this.file = file.raw
      // 文件改变时上传
      // this.submitForm(file)
    },
    handleRemove(file, fileList) {
      this.percentage = 0 //进度条置空
      this.fileList = []
    },
    addSomePeoplePicsForm() {
      this.form.productSlideshow = JSON.stringify(this.fileListImages)
      console.log(this.fileListImages)
      console.log(file)
      console.log(fileList)
      alert(this.form.productSlideshow)
      let self = this;
      this.formPicsData = new FormData();
      this.$refs.uploadPic.submit();
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      uploadFileAll( this.formPicsData, config).then(res => {
        this.form.productSlideshow = res.data;
        this.$message({
          message: '上传成功',
          type: 'success',
          duration:1000
        });
      }).catch(res => {
        this.$message({
          message: '上传成功',
          type: 'success',
          duration:1000
        });
      });
    }
  }
};
</script>
